package Thread.ReadWriteLock;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Main {
    public static void main(String[] args) throws Exception {
        Counter counter = new Counter();
        var t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                counter.inc(1);
            }
        });
        var t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("t2: "+Arrays.toString(counter.get()));
            }
        });
        var t3 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("t3: "+Arrays.toString(counter.get()));
            }
        });
        t1.start();
        t2.start();
        t3.start();

    }
}

class Counter {
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();
    private int[] counts = new int[10];

    public void inc(int index){
        writeLock.lock();
        try {
            counts[index]++;
        } finally {
            writeLock.unlock();
        }
    }

    public void inc2(int index){
        counts[index]++;
    }

    public int[] get(){
        System.out.println("Reading...");
        readLock.lock();
        try {
            System.out.println(Arrays.toString(counts));
            return Arrays.copyOf(counts, counts.length);
        }finally {
            readLock.unlock();
        }
    }

    public int[] get2(){
        return Arrays.copyOf(counts, counts.length);
    }


}
